#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Markdown到A4标准Word文档转换器
专门针对A4页面尺寸优化的转换工具
"""

import re

def convert_markdown_to_a4_html(md_file_path, output_path):
    """将Markdown文件转换为A4标准的HTML"""
    
    with open(md_file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # A4标准HTML模板 (210mm x 297mm)
    html_template = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>类小脑计算平台技术规格书</title>
    <style>
        @page {{
            size: A4;
            margin: 2.54cm 2.54cm 2.54cm 2.54cm; /* 标准1英寸边距 */
        }}
        
        body {{
            font-family: "Times New Roman", "宋体", serif;
            font-size: 12pt;
            line-height: 1.5;
            color: #000;
            margin: 0;
            padding: 0;
            width: 21cm;
            max-width: 21cm;
            background: white;
        }}
        
        .page {{
            width: 21cm;
            min-height: 29.7cm;
            padding: 2.54cm;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            page-break-after: auto;
        }}
        
        h1 {{
            font-size: 18pt;
            font-weight: bold;
            text-align: center;
            margin: 0 0 24pt 0;
            page-break-after: avoid;
            color: #000;
        }}
        
        h2 {{
            font-size: 16pt;
            font-weight: bold;
            margin: 18pt 0 12pt 0;
            page-break-after: avoid;
            color: #000;
        }}
        
        h3 {{
            font-size: 14pt;
            font-weight: bold;
            margin: 12pt 0 6pt 0;
            page-break-after: avoid;
            color: #000;
        }}
        
        h4 {{
            font-size: 12pt;
            font-weight: bold;
            margin: 12pt 0 6pt 0;
            page-break-after: avoid;
            color: #000;
        }}
        
        h5, h6 {{
            font-size: 12pt;
            font-weight: bold;
            margin: 6pt 0 6pt 0;
            page-break-after: avoid;
            color: #000;
        }}
        
        p {{
            margin: 6pt 0;
            text-align: justify;
            text-indent: 0;
        }}
        
        ul, ol {{
            margin: 6pt 0;
            padding-left: 24pt;
        }}
        
        li {{
            margin: 3pt 0;
            line-height: 1.5;
        }}
        
        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 12pt 0;
            font-size: 10pt;
            page-break-inside: avoid;
        }}
        
        th, td {{
            border: 1pt solid #000;
            padding: 6pt;
            text-align: left;
            vertical-align: top;
        }}
        
        th {{
            background-color: #f0f0f0;
            font-weight: bold;
            text-align: center;
        }}
        
        pre {{
            font-family: "Courier New", monospace;
            font-size: 9pt;
            background-color: #f8f8f8;
            border: 1pt solid #ccc;
            padding: 6pt;
            margin: 6pt 0;
            white-space: pre-wrap;
            word-wrap: break-word;
            page-break-inside: avoid;
        }}
        
        code {{
            font-family: "Courier New", monospace;
            font-size: 10pt;
            background-color: #f0f0f0;
            padding: 1pt 2pt;
        }}
        
        hr {{
            border: none;
            border-top: 1pt solid #000;
            margin: 12pt 0;
        }}
        
        .ascii-art {{
            font-family: "Courier New", monospace;
            font-size: 8pt;
            white-space: pre;
            background-color: #f8f8f8;
            border: 1pt solid #ccc;
            padding: 6pt;
            margin: 6pt 0;
            overflow-x: auto;
            page-break-inside: avoid;
        }}
        
        .page-break {{
            page-break-before: always;
        }}
        
        /* 打印样式 */
        @media print {{
            body {{
                font-size: 12pt;
                line-height: 1.5;
            }}
            .page {{
                box-shadow: none;
                margin: 0;
                padding: 0;
            }}
            h1, h2, h3, h4, h5, h6 {{
                page-break-after: avoid;
            }}
            table, pre, .ascii-art {{
                page-break-inside: avoid;
            }}
        }}
    </style>
</head>
<body>
    <div class="page">
        {content}
    </div>
</body>
</html>'''
    
    # 转换Markdown内容
    html_content = convert_md_content_a4(content)
    
    # 生成完整HTML
    full_html = html_template.format(content=html_content)
    
    # 保存HTML文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(full_html)
    
    print(f"A4标准HTML文档已生成: {output_path}")
    print("\n转换为Word文档的步骤：")
    print("1. 用浏览器打开HTML文件")
    print("2. 按Ctrl+P打印，选择'另存为PDF'或直接打印")
    print("3. 或在Word中打开HTML文件，另存为.docx格式")
    print("4. Word会自动识别A4页面设置")

def convert_md_content_a4(content):
    """转换Markdown内容为A4优化的HTML"""
    lines = content.split('\n')
    html_lines = []
    in_code_block = False
    table_buffer = []
    in_table = False
    
    for i, line in enumerate(lines):
        # 代码块处理
        if line.startswith('```'):
            if in_code_block:
                # 检查是否是ASCII艺术
                code_content = '\n'.join(html_lines[html_lines.index('<pre>') + 1:])
                if any(char in code_content for char in ['┌', '└', '├', '│', '+-', '|']):
                    html_lines[html_lines.index('<pre>')] = '<div class="ascii-art">'
                    html_lines.append('</div>')
                else:
                    html_lines.append('</pre>')
                in_code_block = False
            else:
                html_lines.append('<pre>')
                in_code_block = True
            continue
        
        if in_code_block:
            html_lines.append(line)
            continue
        
        # 表格处理
        if '|' in line and line.strip().startswith('|') and line.strip().endswith('|'):
            if not in_table:
                in_table = True
                table_buffer = []
                html_lines.append('<table>')
            
            cells = [cell.strip() for cell in line.strip('|').split('|')]
            if not all(re.match(r'^[-:]+$', cell.strip()) for cell in cells if cell.strip()):
                if len(table_buffer) == 0:  # 第一行作为表头
                    html_lines.append('<thead><tr>')
                    for cell in cells:
                        html_lines.append(f'<th>{cell}</th>')
                    html_lines.append('</tr></thead><tbody>')
                else:
                    html_lines.append('<tr>')
                    for cell in cells:
                        html_lines.append(f'<td>{cell}</td>')
                    html_lines.append('</tr>')
                table_buffer.append(line)
            continue
        else:
            if in_table:
                html_lines.append('</tbody></table>')
                in_table = False
                table_buffer = []
        
        # 标题处理
        if line.startswith('#'):
            level = 0
            for char in line:
                if char == '#':
                    level += 1
                else:
                    break
            content_text = line[level:].strip()
            
            # 主要章节添加分页
            if level <= 2 and i > 0:
                html_lines.append('<div class="page-break"></div>')
            
            html_lines.append(f'<h{level}>{content_text}</h{level}>')
        
        # 分隔线
        elif re.match(r'^-{3,}$', line.strip()):
            html_lines.append('<hr>')
        
        # 列表项
        elif re.match(r'^\s*[-*+]\s+', line):
            content_text = re.sub(r'^\s*[-*+]\s+', '', line)
            if not any('<ul>' in hl for hl in html_lines[-3:]):
                html_lines.append('<ul>')
            html_lines.append(f'<li>{content_text}</li>')
            # 检查下一行是否还是列表项
            if i + 1 < len(lines) and not re.match(r'^\s*[-*+]\s+', lines[i + 1]):
                html_lines.append('</ul>')
        
        # 数字列表
        elif re.match(r'^\s*\d+\.\s+', line):
            content_text = re.sub(r'^\s*\d+\.\s+', '', line)
            if not any('<ol>' in hl for hl in html_lines[-3:]):
                html_lines.append('<ol>')
            html_lines.append(f'<li>{content_text}</li>')
            # 检查下一行是否还是列表项
            if i + 1 < len(lines) and not re.match(r'^\s*\d+\.\s+', lines[i + 1]):
                html_lines.append('</ol>')
        
        # 空行
        elif not line.strip():
            html_lines.append('')
        
        # 普通段落
        else:
            # 处理行内格式
            line = re.sub(r'`([^`]+)`', r'<code>\1</code>', line)
            line = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', line)
            line = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', line)
            html_lines.append(f'<p>{line}</p>')
    
    # 处理未关闭的表格
    if in_table:
        html_lines.append('</tbody></table>')
    
    return '\n'.join(html_lines)

if __name__ == "__main__":
    input_file = "cerebellar_platform_spec_ui_upgraded(1).md"
    output_file = "cerebellar_platform_spec_A4.html"
    
    try:
        convert_markdown_to_a4_html(input_file, output_file)
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
